package cn.wangxl.group.rpc.discover;

import cn.wangxl.group.rpc.zookeeper.MyZkSerializer;
import com.alibaba.fastjson.JSON;
import org.I0Itec.zkclient.ZkClient;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Deacription ZookeeperServiceInfoDiscoverer
 * @Author 20112128
 * @Date 2020/9/18 10:20
 **/
public class ZookeeperServiceInfoDiscoverer implements ServiceInfoDiscoverer{

    private String address;

    private ZkClient zkClient;

    private String centerRootPath = "/simple-rpc";

    @Override
    public List<ServiceInfo> getServiceInfo(String name) {
        if(zkClient == null){
            zkClient = new ZkClient(address);
        }
        zkClient.setZkSerializer(new MyZkSerializer());
        List<String> nodes = zkClient.getChildren(centerRootPath + "/" + name);

        List<ServiceInfo> list = new ArrayList<>();

        if(nodes!=null && nodes.size()>0){
            nodes.stream().forEach(node->{
                try {
                    node = URLDecoder.decode(node,"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                ServiceInfo serviceInfo = JSON.parseObject(node,ServiceInfo.class);
                list.add(serviceInfo);
            });

        }
        return list;
    }

    public ZookeeperServiceInfoDiscoverer(String address) {
        this.address = address;
    }
}
